﻿package com.krds
{
	
	import be.nascom.flash.net.upload.UploadPostHelper;
	
	import com.adobe.images.JPGEncoder;
	import com.greensock.TweenMax;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.getClassByAlias;
	import flash.sampler.getSamples;
	import flash.sampler.getSize;
	import flash.system.System;
	import flash.ui.Mouse;
	import flash.utils.ByteArray;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	public class Main extends MovieClip implements IMain
	{
		private var timer:Timer = new Timer(500);
		private var clock:Timer = new Timer(1000);
		public var proArr:Array= new Array("duo_curacao","duo_mauve","fdt_compo","mono_candy","mono_caro","mono_curacao","mono_geisha","mono_picnic",
		"multi_pin","vernis_cherry","vernis_curacao","vernis_jaune","vernis_jealous","verre_berries");
		////	public var proArr:Array= new Array("duo_curacao","mono_caro","fdt_compo","mono_candy","multi_black_compo","vernis_cherry","vernis_curacao");
		public var productArr:Array= new Array;
		public var currMousex:Number;
		private var callbackUrl:String;
		private var signedRequest:String;
		private var count:Number = 0;
		
		var newOne:Number = 0;
		
		public function Main()
		{
			stop();
			var paramObj:Object = LoaderInfo(this.loaderInfo).parameters;
			
			callbackUrl		=	String(paramObj["callback_url"]);
			signedRequest	=	String(paramObj["signed_request"]);
			
			
			this.loaderInfo.addEventListener(Event.COMPLETE, loadProduct);
	
			ExternalInterface.addCallback("rulesDialogOpened",stopTimer);
			ExternalInterface.addCallback("rulesDialogClosed",startTimer);
			
		}
		private function stopTimer():void
		{
			clock.stop();
			timer.stop();
		}
		private function startTimer():void
		{
			timer.start();
			clock.start();
		}
		private function loadProduct(e:Event = null):void
		{
			trace("loadedd")
			var randomArr:Number = Math.round(Math.random()*(proArr.length-1))
			var name:String = String(proArr.splice(randomArr,1));
			//var _url:URLRequest = new URLRequest("product/"+name+".swf")
			var _url:URLRequest = new URLRequest("include/swf/products/"+name+".swf")
			var loader:Loader = new Loader ();
			loader.name = name;
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoadInit);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,loadProduct);			
			loader.load(_url);	
			
		}
		private function onProgress(e:ProgressEvent):void
		{
			if(loadingMc != null)
			{
				var per:Number = 33*Number(productArr.length)+Math.round((e.bytesLoaded/e.bytesTotal)*33)
				loadingMc.txt.text = "Veuillez patienter pendant le chargement "+per+"%";
			}
		}
		private function onLoadInit(e:Event):void
		{
			
			var loaderInfo:LoaderInfo = LoaderInfo(e.target)  
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS,onProgress);
			loaderInfo.removeEventListener(Event.COMPLETE,onLoadInit);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,loadProduct);
			
			productArr.push(loaderInfo.loader);

			if(proArr.length > 0 )
			{
				loadProduct();
			}
			if(productArr.length > 2 )
			{
				gotoSecond();
			}
			
		}
		private function gotoSecond():void
		{
			
			gotoAndStop(2);	
			startPopup.startBtn.buttonMode = true;
			startPopup.startBtn.addEventListener(MouseEvent.CLICK,onStart);
			startPopup.startBtn.addEventListener(MouseEvent.ROLL_OVER,over);
			startPopup.startBtn.addEventListener(MouseEvent.ROLL_OUT,out);
			
			for(var i:int = 1;i<6;i++)
			{
				MovieClip(getChildByName("thumb"+i)).gotoAndStop(i);
				MovieClip(getChildByName("thumb"+i)).numClicked = 0;
			}
		
			
		}
		private function over(e:MouseEvent):void
		{
			e.target.gotoAndStop(2)
		}
		private function out(e:MouseEvent):void
		{
			e.target.gotoAndStop(1)
		}
		private function onStart(e:MouseEvent):void
		{

			
			TweenMax.to(startPopup,.4,{autoAlpha:0})
			Mouse.hide();
			
			timer.addEventListener(TimerEvent.TIMER,addPro);			
			timer.start();
			
			clock.addEventListener(TimerEvent.TIMER,clockFn);			
			clock.start();
			addPro();
			
			addEventListener(MouseEvent.MOUSE_MOVE,flowMouse);	
			addEventListener(MouseEvent.MOUSE_UP,up);
			addEventListener(MouseEvent.MOUSE_DOWN,down);
			
			
			brushMc.mouseEnabled = false;
			currMousex = mouseX;
			TweenMax.to(brushMc,.35,{x:mouseX,y:mouseY});
			brushMc.rotation = 0;
			
		}
		private function flowMouse(e:Event):void
		{
			
			brushMc.rotation += (mouseX- currMousex)/10
			
			if( -35 > brushMc.rotation)
			{
				brushMc.rotation = -35;
			}
			if(brushMc.rotation > 35)
			{
				brushMc.rotation = 35;
			}
			
			currMousex = mouseX;
			brushMc.x = mouseX;
			brushMc.y = mouseY;
		}
		private function up(e:MouseEvent):void
		{
			brushMc.gotoAndStop(1)
		}
		private function down(e:MouseEvent):void
		{
			brushMc.gotoAndStop(2)
			
		}
		private function clockFn(e:TimerEvent):void
		{
			if(clock.currentCount > 19)
			{
				clock.stop();
				Mouse.show();
				brushMc.visible = false;				
				saveImg(null)
				
				
			}
			if(clock.currentCount <= 15)
			{
				timerTxt.text = String(15- Timer(e.currentTarget).currentCount)+" SEC"
					
			}
			
		}
		function saveImg(e:MouseEvent):void {
			var jpgSource:BitmapData = new BitmapData (630, 479);
			jpgSource.draw(drawMc);
			
			
			var jpgEncoder:JPGEncoder = new JPGEncoder(80);
			var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
			
			/* for get count[END] */
			
			//var jpgURLRequest:URLRequest = new URLRequest("/dispatch_home.php?action=flash_upload");
			var jpgURLRequest:URLRequest = new URLRequest("/dispatch_home.php?action=flash_upload&?count="+count);
			jpgURLRequest.method = URLRequestMethod.POST;
			
			var postVariables:Object = {"signed_request":signedRequest};
			jpgURLRequest.data = UploadPostHelper.getPostData('image.jpg',jpgStream,"filedata",postVariables);//here is where the magic happens, filedata will be the name to retrieve the file
			jpgURLRequest.requestHeaders.push( new URLRequestHeader( 'Cache-Control', 'no-cache' ) );			
			jpgURLRequest.requestHeaders.push(new URLRequestHeader('Content-Type', 'multipart/form-data; boundary=' + UploadPostHelper.getBoundary()));
			//trace("Encoded:"+jpgStream);
			var jpgLoader:URLLoader=new URLLoader();
			jpgLoader.dataFormat = URLLoaderDataFormat.BINARY;
			jpgLoader.load(jpgURLRequest);
			jpgLoader.addEventListener(Event.COMPLETE,onComplete);
		}
		function onComplete(evt:Event):void {
			var resultStr:String = String(evt.target.data);
			trace("resultStr:"+resultStr);
			
			if ((resultStr == "0")) {
				ExternalInterface.call("onGameComplete",count);
			}
		}
		private function addPro(e:TimerEvent = null):void
		{

			if(clock.currentCount < 15)
			{	
				newOne++;
				var SymbolClass:Class = productArr[(newOne%productArr.length)].contentLoaderInfo.applicationDomain.getDefinition("product");
				var pro:MovieClip = new SymbolClass();
				pro.name = productArr[(newOne%productArr.length)].name;
				IProduct(pro).startMove();
				displayMc.addChild(pro);
				setChildIndex(brushMc,this.numChildren-1);
				
				
			}else {
				timer.stop();
			}
			
			
		}
		public function removeChildren(mc:IProduct):void
		{
			displayMc.removeChild(MovieClip(mc));
			
			mc = null;
		}
		public function addBitmap(bit:Bitmap):void
		{
			
			drawMc.addChild(bit);
		}
		public function productCliked(name:String):void
		{
			count++;
		 var num:int;
		 trace(name)
			switch (name.substring(0,3))
			{
				case "ver":
					num=1;
					break;
				case "mul":
					num = 2;
					break;
				case "fdt":
					num = 3;
					break;
				case "duo":
					num = 4;
					break;
				case "mon":
					num = 5;
					break;
			}
			if(MovieClip(getChildByName("thumb"+num)) != null)
			{
				MovieClip(getChildByName("thumb"+num)).numClicked ++;
				MovieClip(getChildByName("thumb"+num)).txt.text = String(MovieClip(getChildByName("thumb"+num)).numClicked);
			}
			 
		}
	}
}